<template>
	<view class="uni-container">
		<uni-forms ref="form" v-model="formData" :rules="rules" validateTrigger="bind" @submit="submit">
			<uni-forms-item name="name" label="类别名称" required>
				<uni-easyinput v-model="formData.name" :clearable="false" placeholder="请输入类别名称" />
			</uni-forms-item>
			<uni-forms-item name="description" label="类别描述" required>
				<uni-easyinput v-model="formData.description" :clearable="false" placeholder="请输入类别描述" />
			</uni-forms-item>
			<uni-forms-item name="parent_id" label="父类别">
				<uni-data-picker :value="formData.parent_id" placeholder="请选择父类" collection="opendb-mall-categories" where="parent_id==''" field="_id as value, name as text,sort" orderby="sort asc"
				 @change="changeCate">
				</uni-data-picker>
			</uni-forms-item>
			<uni-forms-item name="icon" label="图标地址">
				<uni-file-picker
					v-model="uploadFiles"
					fileMediatype="image" 
					mode="grid"
					return-type="object"
					@select="selectFile" 
					@success="uploadSucc" 
					@fail="uploadFail"
					@delete="deleteFile"
				/>
			</uni-forms-item>
			<uni-forms-item name="sort" label="排序">
				<uni-number-box v-model="formData.sort" max="10000"></uni-number-box>
			</uni-forms-item>
			<uni-forms-item name="is_hot_show" label="热门显示">
				<switch @change="bindFormData('is_hot_show', $event.detail.value)" :checked="formData.is_hot_show" />
			</uni-forms-item>
			<uni-forms-item name="is_index_show" label="首页显示">
				<switch @change="bindFormData('is_index_show', $event.detail.value)" :checked="formData.is_index_show" />
			</uni-forms-item>
			<view class="uni-button-group">
				<button style="width: 100px;" type="primary" class="uni-button"
					@click="submitForm">{{$t('common.button.submit')}}</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;"><button style="width: 100px;"
						class="uni-button">{{$t('common.button.back')}}</button></navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '@/js_sdk/validator/opendb-mall-categories.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'opendb-mall-categories';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}

	export default {
		data() {
			return {
				formData: {
					"name": "",
					"description": "",
					"icon":"",
					"sort":0,
					"is_hot_show":false,
					"is_index_show":false,
					"parent_id":''
				},
				formDataId:"",
				uploadFiles:[],
				rules: {
					...getValidator(["name", "description", "sort", "is_hot_show","is_index_show","parent_id"])
				}
			}
		},
		onLoad(e) {
			const id = e.id
			this.formDataId = id
			this.getDetail(id)
		},
		methods: {
			changeCate(e){
				const val=e.detail.value;
				this.bindFormData('parent_id',val[val.length-1].value);
			},
			getDetail(id){
				uniCloud.callFunction({
					name: 'shop-api',
					data: {
						action: 'cate/getOne',
						data:{
							id
						}
					}
				}).then(({result}) =>{
					if(result.code==200){
						result.data.id=result.data._id;
						delete result.data._id;
						//result.data.add_date=this.$formatDate(result.data.add_date,'yyyy-MM-dd hh:mm:ss');
						Object.assign(this.formData,result.data);
						if(this.formData.icon){
							this.uploadFiles=[{
								"name":"file.txt",
								"extname":"txt",
								"url":this.formData.icon
							}]
						}
						console.log(this.formData,result)
					}
				})
			},
			// 上传成功
			uploadSucc(e){
				console.log('上传成功',e,this.uploadFiles)
				this.bindFormData('icon',this.uploadFiles.url)
			},
			// 上传失败
			uploadFail(e){
				console.log('上传失败：',e)
			},
			deleteFile(e){
				console.log('删除文件：',e)
				this.bindFormData('icon','')
			},
			selectFile(e){
				console.log('选择文件：',e)
			},
			bindFormData(name,val){
				this.$refs['form'].setValue(name,val);
				this.formData[name]=val;
			},
			/**
			 * 触发表单提交
			 */
			submitForm() {
				this.$refs.form.submit();
			},

			/**
			 * 表单提交
			 * @param {Object} event 回调参数 Function(callback:{value,errors})
			 */
			submit(event) {
				const {
					value,
					errors
				} = event.detail

				// 表单校验失败页面会提示报错 ，要停止表单提交逻辑
				if (errors) {
					return
				}
				uni.showLoading({
					title: '提交中...',
					mask: true
				})
				// 是否启用功能的数据类型转换， 0 正常， 1 禁用
				if (typeof value.status === "boolean") {
					value.status = Number(!value.status)
				}
				uniCloud.callFunction({
					name: 'shop-api',
					data: {
						action: 'cate/edit',
						data:this.formData
					}
				}).then(({result}) =>{
					uni.hideLoading();
					if(result.code==200){
						uni.showToast({
						  title: '修改成功'
						})
						uni.navigateTo({
							url:'./list'
						})
					}else{
						uni.showToast({
						  title: result.message
						})
					}
				})
			}
		}
	}
</script>
<style>
	::v-deep .uni-forms-item__label {
		width: 90px !important;
	}
</style>
